<template>
  <div class="register-container">
    <div class="register-form">
      <div class="form-header">
        <h2>用户注册</h2>
        <p>加入我们，开启电商之旅</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="0"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Iphone"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleRegister"
          />
        </el-form-item>
        
        <el-form-item prop="agreement">
          <div class="agreement">
            <el-checkbox v-model="registerForm.agreement" class="agreement-checkbox"></el-checkbox>
            <label class="agreement-label">我已阅读并同意 <a href="#">《用户服务协议》</a> 和 <a href="#">《隐私政策》</a></label>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            class="register-button"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>
        
        <div class="form-footer">
          <span>已有账号？</span>
          <el-button type="text" @click="$router.push('/login')">立即登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const registerFormRef = ref()
const loading = ref(false)

const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

import { register, checkUsername, checkEmail, checkPhone } from '../api/user'

const validateUsername = async (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (value.length < 3 || value.length > 20) {
    callback(new Error('用户名长度在3-20个字符'))
  } else {
    try {
      const res = await checkUsername(value)
      if (res.data.code === 0 && res.data.data) {
        callback(new Error('用户名已存在'))
      } else {
        callback()
      }
    } catch (e) {
      callback(new Error(res?.data?.message || '用户名校验失败'))
    }
  }
}


const validateEmail = async (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('邮箱格式不正确'))
  } else {
    try {
      const res = await checkEmail(value)
      if (res.data.code === 0 && res.data.data) {
        callback(new Error('该邮箱已注册'))
      } else {
        callback()
      }
    } catch (e) {
      callback(new Error(res?.data?.message || '邮箱校验失败'))
    }
  }
}

const validatePhone = async (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!phoneRegex.test(value)) {
    callback(new Error('手机号格式不正确'))
  } else {
    try {
      const res = await checkPhone(value)
      if (res.data.code === 0 && res.data.data) {
        callback(new Error('该手机号已注册'))
      } else {
        callback()
      }
    } catch (e) {
      callback(new Error(res?.data?.message || '手机号校验失败'))
    }
  }
}


const validatePassword = (rule, value, callback) => {
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{6,20}$/
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (!passwordRegex.test(value)) {
    callback(new Error('密码需6-20位，包含字母和数字'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}


const validateAgreement = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请阅读并同意协议'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { validator: validateUsername, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  agreement: [
    { validator: validateAgreement, trigger: 'change' }
  ]
}

const handleRegister = () => {
  registerFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        const { username, password, phone, email } = registerForm
        const res = await register({ username, password, phone, email })
        loading.value = false
        if (res.code === 0 ) {
          ElMessage.success((res.data.message || '注册成功！请登录'))
          Object.assign(registerForm, {
            username: '',
            email: '',
            phone: '',
            password: '',
            confirmPassword: '',
            agreement: false
          })
          router.push('/login')
        } else {
          ElMessage.error(res.data.message || '注册失败')
        }
      } catch (e) {
        loading.value = false
        ElMessage.error(e?.response?.data?.message || '注册请求失败')
      }
    } else {
      ElMessage.warning('请完善表单信息')
    }
  })
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-form {
  width: 100%;
  max-width: 420px;
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 28px;
}

.form-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.register-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

.form-footer {
  text-align: center;
  color: #909399;
  margin-top: 20px;
}

.form-footer span {
  margin-right: 8px;
}

.agreement {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.agreement-checkbox {
  margin-top: 2px;
}
.agreement-label {
  margin-left: 8px;
  line-height: 1.5;
  color: #606266;
  font-size: 14px;
}

.agreement label {
  margin-left: 8px;
  line-height: 1.5;
  color: #606266;
  font-size: 14px;
}

.agreement a {
  color: #667eea;
  text-decoration: none;
}

</style>